﻿using System.Web.Mvc;

namespace BSF.ServicesResult
{
    public class JsonpResult : JsonResult
    {
        /*
         * ASP.NET MVC 实现 AJAX 跨域请求 http://blog.csdn.net/skyandcode/article/details/12524673
         * return new JsonpResult{ Data = str };  //返回 jsonp 数据，输出回调函数
         * **/
        public JsonpResult()
        {
            JsonRequestBehavior = JsonRequestBehavior.AllowGet;
        }
        public string Callback { get; set; }
        ///<summary>
        ///对操作结果进行处理
        ///</summary>
        ///<paramname="context"></param>
        public override void ExecuteResult(ControllerContext context)
        {
            var httpContext = context.HttpContext;
            var callBack = Callback;
            if (string.IsNullOrWhiteSpace(callBack))
                callBack = httpContext.Request["callback"];//获得客户端提交的回调函数名称
            //返回客户端定义的回调函数
            httpContext.Response.Write(callBack + "(");
            httpContext.Response.Write(Data);//Data 是服务器返回的数据        
            httpContext.Response.Write(");");//将函数输出给客户端，由客户端执行
        }
        /*
         ajax跨域请求
         * C# MVC 后台
        /// <summary>
        /// 操作器和其它操作没什么区别，只是返回值是JsopnpResult结果
        /// </summary>
        /// <returns></returns>
        public ActionResult Index2()
        {
            var str = "{ID :'123', Name : 'asdsa' }";
            return new JsonpResult { Data = str };  //返回 jsonp 数据，输出回调函数
        }
        客户端：
        <scripttype="text/javascript">
            $(function() {
                $(".btn").click(function (){
                    $.ajax({
                        type:"GET",
                        url:"http://localhost:50863/Home/Index3", //跨域URL
                        dataType:"json", 
                        success:function (result){
                            $("#div1").html(result.ID +result.Name);
                        },
                        error:function (XMLHttpRequest, textStatus,errorThrown) {                       
                            alert(errorThrown); // 调用本次AJAX请求时传递的options参数
                        }
                    });
                })
            })
        </script>
        服务端：
        ///<summary>
        ///跨站资源共享实现跨站AJAX请求
        ///</summary>
        ///<returns></returns>
        public ActionResult Index3()
        {
            var str = new { ID="123", Name= "asdsa" };
            HttpContext.Response.AppendHeader("Access-Control-Allow-Origin","*");
            return Json(str, JsonRequestBehavior.AllowGet);
        }
        
        
        ///<summary>
        ///跨站资源共享实现跨站AJAX请求
        ///</summary>
        ///<returns></returns>
        [System.Web.Services.WebMethod]
        [System.Web.Script.Services.ScriptMethod(ResponseFormat = System.Web.Script.Services.ResponseFormat.Json, XmlSerializeString = false, UseHttpGet = true)]
        public void Index3()
        {
            var str = new { ID = "123", Name = "asdsa" };
            
            var response = System.Web.HttpContext.Current.Response;
            response.Clear(); //清空无关信息
            response.Buffer = true; //完成整个响应后再发送
            response.Charset = "GB2312";//设置输出流的字符集-中文
            response.AppendHeader("Content-Disposition", "attachment;filename=Report.doc");//追加头信息
            //response.AppendHeader("Access-Control-Allow-Origin", "*");
            response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");//设置输出流的字符集
            response.ContentType = "text/json";

            //获取回调函数名
            var context = System.Web.HttpContext.Current.Request;
            string callback = context.QueryString["callback"];
            var jsons = JsonConvert.SerializeObject(str);
            response.Write(callback + "(" + jsons + ")");
            response.End();
            //return Json(str, JsonRequestBehavior.AllowGet);
        }
         * 前端ajax
         //ajax跨域请求
        $.ajax({
            async: false,//同步
            url: 'http://localhost:10006/Redbag/Index3?rand=' + new Date(),
            dataType: 'jsonp',
            jsonpCallback: 'success_jsonpCallback', //默认callback  
            //processData: false,
            data: { }, //请求数据   
            timeout: 5000,
            beforeSend: function () {
                //jsonp 方式此方法不被触发。原因可能是dataType如果指定为jsonp的话，就已经不是ajax事件了   
            },
            success: function (data) {
                alert(data.ID);
            },
            complete: function (XMLHttpRequest, textStatus) {
            },
            error: function (xhr) {
                //jsonp 方式此方法不被触发   
                //请求出错处理    
                alert("请求出错(请检查相关度网络状况.)");
            }
        });
        function success_jsonpCallback(data) {
            alert(11);
        }
         */
    }
}
